package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "菜品管理")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加
     * @param dishDTO
     * @return
     */
    @PostMapping
    @ApiOperation("添加菜品")
    public Result insertDish(@RequestBody DishDTO dishDTO){
        log.info("添加菜品");
        dishService.insert(dishDTO);
        String key ="dish_"+ dishDTO.getCategoryId();
        cleanCache(key);
        return Result.success();
    }

    /**
     * 菜品分类
     * @param dto
     * @return
     */
    @GetMapping("page")
    @ApiOperation("菜品分类")
    public Result<PageResult> page(DishPageQueryDTO dto){
        log.info("分页查询:{}",dto);
       PageResult pageResult= dishService.page(dto);
        return Result.success(pageResult);
    }

    /**
     * 批量删除菜品接口
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation("批量删除菜品接口")
    public Result deleteByIds(Long[] ids){
        log.info("批量删除菜品:{}",ids);
        dishService.deleteByIds(ids);
        cleanCache("dish_*");
        return  Result.success();
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @ApiOperation("根据id查询菜品")
    public Result<DishVO> getById(@PathVariable Long id){
        log.info("获取{}的菜品",id);
        DishVO dishVO = dishService.getById(id);
        return Result.success(dishVO);
    }

    /**
     * 修改菜品信息
     * @param dishDTO
     * @return
     */
    @PutMapping
    @ApiOperation("修改菜品信息")
    public Result update(@RequestBody DishDTO dishDTO){
        log.info("修改菜品信息");
        dishService.update(dishDTO);
        cleanCache("dish_*");
        return Result.success();
    }

    @GetMapping("list")
    public Result<List<DishDTO>> list(Long categoryId){
        List<DishDTO> list = dishService.getByIds(categoryId);
        return Result.success(list);
    }
    @PostMapping("status/{status}")
    @ApiOperation("菜品起售、停售")
    public Result openOrClose(@PathVariable Integer status,Long id){
        log.info("菜品起售、停售");
        dishService.openOrClose(status,id);
        cleanCache("dish_*");
        return  Result.success();
    }
    //清除缓存方法
    private void cleanCache(String key){
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }
}
